package com.apexcode.friend.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.apexcode.common.core.domain.TableDataInfo;
import com.apexcode.friend.domain.exam.dto.ExamQueryDTO;
import com.apexcode.friend.domain.exam.vo.ExamVO;
import com.apexcode.friend.manager.ExamCacheManager;
import com.apexcode.friend.mapper.exam.ExamMapper;
import com.apexcode.friend.service.exam.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName ExamServiceImpl
 * @Description
 * @Author ZJX
 * @Date 2025/2/6 18:05
 * @Version 1.0
 **/
@Service
public class  ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        return examMapper.selectExamList(examQueryDTO);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        //从redis当中获取  竞赛列表的数据
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            examVOList = list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType(), null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, null);
            total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
//        assembleExamVOList(examVOList);
        return TableDataInfo.success(examVOList, total);
    }

    @Override
    public String getFirstQuestion(Long examId) {
        checkAndRefresh(examId);
        return examCacheManager.getFirstQuestion(examId).toString();
    }


    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }

//    private void assembleExamVOList(List<ExamVO> examVOList) {
//        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
//        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
//        if (CollectionUtil.isEmpty(userExamIdList)) {
//            return;
//        }
//        for (ExamVO examVO : examVOList) {
//            if (userExamIdList.contains(examVO.getExamId())) {
//                examVO.setEnter(true);
//            }
//        }
//    }

}
